import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/login.vue'
import Home from '../views/home.vue'
import User from '../views/user/user.vue'
import Roles from '../views/power/roles.vue'
import Rights from '../views/power/rights.vue'
import Goods from '../views/product/goods.vue'
import Params from '../views/product/params.vue'
import Categories from '../views/product/categories.vue'
import Add from '../views/product/add.vue'
import Report from '../views/report/report.vue'
import Orders from '../views/orders/orders.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/', redirect: '/login'
  },
  {
    path: '/login', component: Login
  },
  {
    path: '/home', component: Home,
    children: [
      {
        path: '/users', component: User
      },
      {
        path: '/roles', component: Roles
      },
      {
        path: '/rights', component: Rights
      },
      {
        path: '/goods', component: Goods
      },
      {
        path: '/params', component: Params
      },
      {
        path: '/categories', component: Categories
      },
      {
        path: '/add', component: Add
      },
      {
        path: '/reports', component: Report
      },
      {
        path: '/orders', component: Orders
      },
    ]
  }
]

const router = new VueRouter({
  mode: 'hash',
  routes
})
router.beforeEach((to, from, next) => {
  const token = window.sessionStorage.getItem('token')
  if (to.path !== '/login') {
    if (token) {
      next()
    } else {
      next({ path: '/login' })
    }
  }
  next()
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

export default router
